<template>
  <div class="partner-container">
    <el-card class="partner-card">
      <template #header>
        <div class="card-header">
          <h3>找搭子</h3>
          <el-button type="primary" @click="dialogVisible = true">发布新帖</el-button>
        </div>
      </template>

      <!-- 帖子筛选 -->
      <div class="filter-bar">
        <el-input
          v-model="searchSubject"
          placeholder="按主题搜索"
          @input="handleSearch"
        />
        <el-select
          v-model="statusFilter"
          placeholder="筛选状态"
          @change="handleStatusFilter"
        >
          <el-option label="全部" value="" />
          <el-option label="活跃" value="ACTIVE" />
          <el-option label="已匹配" value="MATCHED" />
        </el-select>
      </div>

      <!-- 帖子列表 -->
      <div class="post-list">
        <el-empty v-if="posts.length === 0 && !loading" description="暂无内容" />
        <el-skeleton v-if="loading" :rows="5" animated />
        <el-card
          v-for="post in posts"
          :key="post.id"
          class="post-item"
        >
          <div class="post-header">
            <div class="user-info">
              <el-avatar style="width: 40px; height: 40px" />
              <span class="username">{{ post.username }}</span>
            </div>
            <span class="post-time">{{ post.createTime }}</span>
          </div>
          <div class="post-content">
            <h4>{{ post.title }}</h4>
            <p>{{ post.content }}</p>
          </div>
          <div class="post-footer">
            <el-button
                type="primary"
                text
                @click="contact(post)"
                :disabled="post.userId === currentUser?.id"
            >
              {{ post.userId === currentUser?.id ? '自己的请求' : '联系Ta' }}
            </el-button>
            <el-button type="info" text @click="viewDetails(post.id)">查看详情</el-button>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <el-pagination
        v-if="totalPages > 1"
        v-model:current-page="currentPage"
        :total="totalItems"
        :page-size="pageSize"
        layout="prev, pager, next"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 发布新帖对话框 -->
    <el-dialog v-model="dialogVisible" title="发布新帖">
      <el-form :model="newPost" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="newPost.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="newPost.description"
            type="textarea"
            :rows="4"
            placeholder="请输入描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="主题">
          <el-select v-model="newPost.subject" placeholder="请选择主题">
            <el-option label="学习" value="学习"></el-option>
            <el-option label="运动" value="运动"></el-option>
            <el-option label="娱乐" value="娱乐"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间">
          <el-input v-model="newPost.preferredTime" placeholder="请输入时间"></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="newPost.contactMethod" placeholder="请输入联系方式"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPost">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 数据
const posts = ref([])
const currentUser = ref(null)
const loading = ref(false)
const searchSubject = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const totalPages = ref(0)
const dialogVisible = ref(false)
const newPost = ref({
  title: '',
  description: '',
  subject: '',
  preferredTime: '',
  contactMethod: ''
})

// 获取当前用户
const fetchCurrentUser = async () => {
  try {
    const res = await axios.get('/auth/user-info', {
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      }
    })
    if (res.data) {
      currentUser.value = res.data
      console.log('当前用户信息:', res.data);  // 添加日志，检查用户信息是否正确返回
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    ElMessage.error('获取用户信息失败，请稍后再试')
  }
}

// 获取帖子列表
const fetchPosts = async () => {
  loading.value = true
  try {
    const response = await axios.get('/partners', {
      params: {
        subject: searchSubject.value,
        status: statusFilter.value,
        page: currentPage.value - 1,
        size: pageSize.value
      }
    })
    posts.value = response.data.content.map(post => ({
      id: post.id,
      userId: post.user.id,  // 添加
      username: post.user.username,
      title: post.title,
      content: post.description,
      createTime: new Date(post.createdAt).toLocaleString()
    }))
    totalItems.value = response.data.totalElements
    totalPages.value = response.data.totalPages
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    ElMessage.error('获取帖子列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 提交帖子
const submitPost = async () => {
  try {
    // 确保用户已登录
    if (!currentUser.value || !currentUser.value.id) {
      ElMessage.error('请先登录')
      return
    }

    if (!newPost.value.title || !newPost.value.description || !newPost.value.subject || !newPost.value.preferredTime || !newPost.value.contactMethod) {
      ElMessage.error('请填写完整信息')
      return
    }

    const payload = {
      ...newPost.value,
      userId: currentUser.value.id // 使用当前用户的ID
    }

    console.log('提交的数据:', payload);

    const response = await axios.post('/partners', payload, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })

    console.log('发布成功响应:', response);

    ElMessage.success('发布成功')
    dialogVisible.value = false
    fetchPosts()
    newPost.value = {
      title: '',
      description: '',
      subject: '',
      preferredTime: '',
      contactMethod: ''
    }
  } catch (error) {
    const errorMessage = error.response?.data?.message || '未知错误'
    console.error('发布失败:', error);
    ElMessage.error(`发布失败：${errorMessage}`)
  }
}


// 联系
const contact = async (post) => {
  try {
    // 检查是否尝试匹配自己的请求
    if (post.userId === currentUser.value.id) {
      ElMessage.warning('不能匹配自己的请求')
      return
    }

    const response = await axios.post(`/partners/${post.id}/matches`, null, {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    })
    ElMessage.success('匹配成功！')
    fetchPosts() // 刷新列表
  } catch (error) {
    const errorMsg = error.response?.data?.message || '匹配失败'
    ElMessage.error(`匹配失败：${errorMsg}`)
  }
}

// 查看详情
import { useRouter } from 'vue-router' // 引入 useRouter 钩子
const router = useRouter()

const viewDetails = (postId) => {
  console.log('查看详情:', postId)
  router.push({ name: 'PostDetail', params: { id: postId } })
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPosts()
}

// 处理状态筛选
const handleStatusFilter = () => {
  currentPage.value = 1
  fetchPosts()
}

// 处理分页
const handlePageChange = (page) => {
  currentPage.value = page
  fetchPosts()
}

onMounted(() => {
  fetchPosts()
  fetchCurrentUser()
})

</script>

<style scoped>
.partner-container {
  padding: 20px;
}

.partner-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.post-list {
  margin-top: 20px;
}

.post-item {
  margin-bottom: 20px;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.username {
  font-weight: bold;
}

.post-time {
  color: #999;
  font-size: 14px;
}

.post-content {
  margin-bottom: 15px;
}

.post-content h4 {
  margin-bottom: 10px;
  color: #333;
}

.post-content p {
  color: #666;
  line-height: 1.5;
}

.post-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}
</style>